package controllers.customer;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import services.CustomerService;
import controllers.AbstractController;
import domain.Customer;
import forms.CustomerForm;


@Controller
@RequestMapping("/security/registration")
public class RegisterCustomerController extends AbstractController  {
	@Autowired
	private CustomerService customerService;

	// Creation
	@RequestMapping(value = "/registerCustomer", method = RequestMethod.GET)
	public ModelAndView registration() {
		ModelAndView result;
		CustomerForm customerForm;
		Boolean isAdministrator = false;

		customerForm = new CustomerForm();

		result = new ModelAndView("security/registration/registerCustomer");
		result.addObject("customerForm", customerForm);
		result.addObject("isAdministrator", isAdministrator);

		return result;
	}

	// Edition
	@RequestMapping(value = "/registerCustomer", method = RequestMethod.POST, params = "save")
	public ModelAndView save(@Valid CustomerForm customerForm,BindingResult binding) {
		ModelAndView result;
		Customer customer;

		if (binding.hasErrors()) {
			result = createEditModelAndView(customerForm);
		} else {
			try {
				if (!customerForm.getAcceptConditions()) {
					result = createEditModelAndView(customerForm,"security.commit.noAcceptConditions");
				} else if (!customerForm.getPassword().equals(customerForm.getRepeatPassword())) {
					result = createEditModelAndView(customerForm,"security.commit.passwordDifferents");
				} else {

					customer = customerService.reconstruct(customerForm);
					
					customerService.save(customer);
					result = new ModelAndView("redirect:../../");
				}
			} catch (Throwable oops) {

				result = createEditModelAndView(customerForm, "customer.commit.error");
			}
		}
		Boolean isAdministrator = false;
		result.addObject("isAdministrator", isAdministrator);
		return result;
	}

	// Ancillary methods
	protected ModelAndView createEditModelAndView(CustomerForm customer) {
		ModelAndView result;

		result = createEditModelAndView(customer, null);

		return result;
	}

	protected ModelAndView createEditModelAndView(CustomerForm customer, String message) {
		ModelAndView result;

		result = new ModelAndView("security/registration/registerCustomer");

		result.addObject("customer", customer);
		result.addObject("message", message);

		return result;
	}

}
